package com.three.box.network.kt

import com.jiongbull.jlog.JLog
import com.three.box.network.HeaderInterceptor
import com.three.box.network.TokenInterceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

class Retrofit2Mgr {

    companion object {
        val instance: Retrofit2Mgr by lazy {
            Retrofit2Mgr()
        }
    }

    private val mRtfContainer = mutableMapOf<String, Retrofit>()

    /**
     * @param baseUrl
     * @return
     * @desc 根据baseUrl生成Retrofit实例
     */
    fun getRetrofit(baseUrl: String): Retrofit {
        return mRtfContainer[baseUrl] ?: genRetrofit(baseUrl)
    }

    private fun genRetrofit(baseUrl: String): Retrofit {
        val loggingInterceptor = HttpLoggingInterceptor { message: String? ->
            showRetrofitLog(message)
        }.setLevel(HttpLoggingInterceptor.Level.BODY)
        val okHttpClient = OkHttpClient.Builder()
            .readTimeout(30, TimeUnit.SECONDS)
            .connectTimeout(30, TimeUnit.SECONDS)
            .addInterceptor(loggingInterceptor)
            .addInterceptor(HeaderInterceptor())
            .addInterceptor(TokenInterceptor())
            .build()

        val retrofit = Retrofit.Builder()
            .baseUrl(baseUrl) // 设置网络请求的Url地址
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create()) // 设置数据解析器
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build()


        mRtfContainer[baseUrl] = retrofit

        return retrofit
    }

    /**
     * 打印日志
     * 返回的是json，就打印格式化好了的json，不是json就原样打印
     */
    private fun showRetrofitLog(message: String?) {
        if (message == null || message.length > 3000) {
            return
        }
        if (message.startsWith("{")) {
            JLog.json(message)
        } else {
            JLog.e("Retrofit:", message)
        }
    }
}